<?php

class Process_Image_Model extends CI_Model {
	function generate_code($length) {
		/**
		 * credit to Latavish
		 * source http://codeigniter.com/forums/viewthread/80610/
		 */
		if ($length <= 0) {
			return false;
		}

		$code = "";
		$chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
		srand((double)microtime() * 1000000);
		for ($i = 0; $i < $length; $i++) {
			$code = $code . substr($chars, rand() % strlen($chars), 1);
		}
		return $code;

	}

	function process_image($token, $id) {
		$uploads = (array)$this -> upload -> data();

		
		if (isset($uploads)) {
			//generate random string of chars
			$randomName = $this -> generate_code(12);
			$newImageName = $randomName . $uploads['file_ext'];

			$this -> load -> library('image_lib');

			if ($token == 1) {
				//create thumb-nails for idea
				$config['image_library'] = 'gd2';
				$config['source_image'] = $uploads['full_path'];
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = '';
				$config['master_dim'] = 'width';
				$config['quality'] = 75;
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 300;
				$config['height'] = 200;
				$config['new_image'] = "./images/upload/ideas/thumbs/" . $newImageName;

				$this -> image_lib -> initialize($config);
				if (!$this -> image_lib -> resize()) {
					echo $this -> image_lib -> display_errors();
				} else {
					rename($uploads['full_path'], './images/upload/ideas/' . $newImageName);
					$data = array(
						'idea_image' => $newImageName
						);
					$this->db->where('idea_id', $id);
					$this->db->update('idea', $data);
					
					return $newImageName;
				}
			}else if($token == 2){
				//create thumbnails for user
				$config['image_library'] = 'gd2';
				$config['source_image'] = $uploads['full_path'];
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = '';
				$config['master_dim'] = 'height';
				$config['quality'] = 75;
				$config['maintain_ratio'] = TRUE;
				$config['height'] = 60;
				$config['width']= 65;
				$config['new_image'] = "./images/upload/user/thumbs/" . $newImageName;
				
				$this -> image_lib -> initialize($config);
				if (!$this -> image_lib -> resize()) {
					echo $this -> image_lib -> display_errors();
				} else {
					rename($uploads['full_path'], './images/upload/user/' . $newImageName);
					$data = array(
						'user_profilepict' => $newImageName
						);
					$this->db->where('user_id', $id);
					$this->db->update('user', $data);
					
					return $newImageName;
				}
				
			}else{
				echo "error";
			}

		}
	}

}
?>